const express = require('express');
const app = express();
const fs = require('fs');
const path = require('path')

var bodyParser = require('body-parser');
app.use(bodyParser());

function sameplify(obj1, obj2) {
    const keys = keys(obj1)
    keys.forEach(element => {
        obj1[element] = obj2[element]
    })
    // obj1.startTime = obj2.startTime;
    // obj1.endTime = obj2.endTime;
    // obj1.statu = obj2.statu;
    // obj1.workDetail = obj2.workDetail;
}

//全局跨域配置
app.all('*', function (req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    res.header('Access-Control-Allow-Methods', '*');
    res.header('Content-Type', 'application/json;charset=utf-8');
    next();
});
//全局数据信息
//任务列表所在
let workfilePath = path.resolve(__dirname, "./dataSource.json")


// <--mainPage-->
//  mainPage-----任务列表获取
app.get('/mainPage', (req, res) => {
    let dataMsg = fs.readFileSync(workfilePath)
    let listItem = JSON.parse(dataMsg.toString())
    res.send({ listItem });
    console.log('get任务列表获取 /mainPage');
});

//  mianPage/addWork-----任务列表添加
app.post('/mainPage/addWork', (req, res) => {
    let dataMsg = fs.readFileSync(workfilePath)
    let listItem = JSON.parse(dataMsg.toString())
    // 合并提交的数据并存储
    const adder = req.body
    const newList = [...listItem, adder];
    fs.writeFileSync(workfilePath, JSON.stringify(newList))
    res.send()
    console.log('post任务列表添加 /mainPage');
});

//更新任务列表内容
app.post('/mainPage/workChange', (req, res) => {
    let dataMsg = fs.readFileSync(workfilePath)
    let listItem = JSON.parse(dataMsg.toString())
    // 合并提交的数据并存储
    const newItem = req.body
    console.log(req.body)
    listItem.forEach(element => {
        if (element.startTime == newItem.startTime) {
            sameplify(element, newItem)
        }
    });
    const newList = listItem
    fs.writeFileSync(workfilePath, JSON.stringify(newList))
    res.send()
    console.log('post更新任务列表内容 /mainPage/workChange');
});


app.listen(8083, () => {
    console.log('Server is running at http://localhost:8083')
});

// function change() {
//     let dataMsg = fs.readFileSync(workfilePath)
//     let listItem = JSON.parse(dataMsg.toString())
//     console.log(listItem)
//     listItem.forEach(element => {
//         element.workDetail = element.workDetail.value
//         element.startTime = element.startTime.value
//         element.endTime = element.endTime.value
//         element.statu = element.statu.value
//     });
//     console.log(listItem)
//     // const newList = listItem
//      fs.writeFileSync(workfilePath, JSON.stringify(listItem))
// }
// change()